package com.ls.demo.tcp.server;

import com.ls.demo.tcp.config.TcpServerChannelInitializer;
import com.ls.demo.tcp.config.TcpServerProperties;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.net.InetSocketAddress;

/**
 * @author liShan
 * @date 2019/8/28 15:49
 */
@Component
public class NettyTcpServer implements Runnable {

    @Resource
    private TcpServerProperties tcpServerProperties;

    @Resource
    private EventLoopGroup bossEventLoopGroup;

    @Resource
    private EventLoopGroup workEventLoopGroup;

    @Resource
    private ServerBootstrap serverBootstrap;

    @Resource
    private TcpServerChannelInitializer tcpServerChannelInitializer;

    /**
     * 开启Netty tcp server服务
     */
    public ChannelFuture start(){
        serverBootstrap.group(bossEventLoopGroup, workEventLoopGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(tcpServerChannelInitializer)
                .childOption(ChannelOption.SO_KEEPALIVE, tcpServerProperties.getTcpKeepAlive())
        ;
        ChannelFuture channelFuture = null;
        try {
            channelFuture = serverBootstrap.bind(new InetSocketAddress(tcpServerProperties.getPort())).sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return channelFuture;
    }

    @Override
    public void run() {
        ChannelFuture channelFuture = this.start();
        if (null != channelFuture){
            try {
                channelFuture.channel().closeFuture().sync();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
